#include "registrar.h"

using namespace std;

registrar::registrar(int nodeID, int programID)
{
	this->nodeID = nodeID;

	configSettings = new Config(ConfigFile);

	char idBuff[20];
	sprintf(idBuff, "commitPort%d", programID);

	int listenUDPPort = configSettings->Read(idBuff, 0);
	
	//建立UDP服务器
	listen_fd = Socket(AF_INET, SOCK_DGRAM, 0);

	bzero(&local_addr, sizeof(local_addr));
	local_addr.sin_family = AF_INET;
	local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	local_addr.sin_port = htons(listenUDPPort);

	cout<<"UDP server listen on port "<<listenUDPPort<<endl;
	Bind(listen_fd, (SA *)&local_addr, sizeof(SA));
}

registrar::~registrar()
{
	Close(listen_fd);
	delete configSettings;
}

void registrar::sendMessage(int toNodeID, int toProgramID, char* buff, int buffSize)
{
	char temp[1024];
	//以此将目的节点号，目的程序号，本节点号，数据写入缓存区temp中
	int n = snprintf(temp, sizeof(temp), "%d#%d#%d#%s", toNodeID, toProgramID, nodeID, buff);

	//获得网络层监听应用层数据的UDP端口
	int netDevicePort = configSettings->Read("localListenPort", 0);
	local_addr.sin_port = htons(netDevicePort);

	//将应用层数据发送到网络层
	cout<<"send to localhost, port "<<netDevicePort<<endl;
	Sendto(listen_fd, temp, n, 0, (SA *)&local_addr, sizeof(SA));
}

int registrar::getSockFd()
{
	return listen_fd;
}
